<?php
namespace Think;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: feiyanger <xiaoxiaochumei.com>
// +----------------------------------------------------------------------
/**
 * 七牛云TP上传和下载图片封装
 * 此类仅为实现图片上传下载，所以其他文件操作方法没有封装，可以自行完善
 * 配置到common/config.php下
 *'QINIU_CONFIG'=>array(
 * 'Secret_Key' => 'KRngBBE8dEI2anOGNpeQvOtlKoogcMaNmx7mU_tq',
 *'Access_Key' => '1jHOvCW0icxZff4yAlzmV8QjaJppCPjPbQNBkq_X',
 *'domain' => 'olhzg90fe.bkt.clouddn.com',
 *'Bucket_Name' => 'feiyangergogogo'
 *),
 */
class Qiniu{
  private $obj = '';
  private $config = '';
  public function __construct(){
    $this->config = C('QINIU_CONFIG');
    Vendor('qiniu.autoload');//七牛云sdk存放到Vendor文件夹下
  }
  /**
   * 权鉴获取
   * @return [obj]
   */
  private function getAuth(){
    // 需要填写你的 Access Key 和 Secret Key
    $accessKey = $this->config['Access_Key'];
    $secretKey = $this->config['Secret_Key'];
    // 构建鉴权对象
    $auth = new Auth($accessKey, $secretKey);
    return $auth;
  }
  /**
   * 文件上传
   * @param  [string] $name      [文件名]
   * @param  [string] $localpath [文件物理地址]
   * @return [array]            [数组]
   */
  public function upload($name,$localpath){
    $auth = $this->getAuth();
    // 要上传的空间
    $bucket = $this->config['Bucket_Name'];
    // 生成上传 Token
    $token = $auth->uploadToken($bucket);
    // 要上传文件的本地路径
    $filePath = $localpath;
    // 上传到七牛后保存的文件名
    $key = $name;
    // 初始化 UploadManager 对象并进行文件的上传。
    $uploadMgr = new UploadManager();
    // 调用 UploadManager 的 putFile 方法进行文件的上传。
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
    // http://olhzg90fe.bkt.clouddn.com/img.jpg
    $baseUrl = 'http://'.$this->config['domain'].'/'.$ret['key'];
    if ($err !== null) {
        $mes = array(
          'status' => false,
          'message' => $err
        );
    } else {
      $mes = array(
        'status' => true,
        'message' => $ret,
        'file_url'=>$this->downloadToken($baseUrl)
      );
    }
    return $mes;
  }
  /**
   * 文件下载
   * @param  [string] $baseUrl [文件外链]
   * @return [string]          [可访问url]
   */
  public function downloadToken($baseUrl){
    $auth = $this->getAuth();
    // 对链接进行签名
    $signedUrl = $auth->privateDownloadUrl($baseUrl);
    return $signedUrl?$signedUrl:'';
  }
}
